package com.ruoyi.system.utils;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.system.domain.ComUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUserUtil {

    public static ComUser getSecurityUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            throw new IllegalArgumentException("No authenticated user found");
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof String) {
            String userJson = (String) principal;
            return JSON.parseObject(userJson, ComUser.class);
        } else if (principal instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) principal;
            // 如果需要，可以将LoginUser转换为ComUser
            // 例如：return convertToComUser(loginUser);
            throw new IllegalArgumentException("Principal is a LoginUser, but expected a JSON string");
        } else {
            throw new IllegalArgumentException("Principal is neither a String nor a LoginUser");
        }
    }

    // 如果需要，可以添加一个方法来将LoginUser转换为ComUser
    //private static ComUser convertToComUser(LoginUser loginUser) {
        // 实现转换逻辑
        // 例如：
        // ComUser comUser = new ComUser();
        // comUser.setUsername(loginUser.getUsername());
        // ...
        // return comUser;
    //}

    public static String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            throw new IllegalArgumentException("No authenticated user found");
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof LoginUser) {
            return ((LoginUser) principal).getUsername();
        } else if (principal instanceof ComUser) {
            return ((ComUser) principal).getUsername();
        } else {
            throw new IllegalArgumentException("Principal is neither a LoginUser nor a ComUser");
        }
    }
}